from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SPU, Brand, GoodsCategory
from meiduo_admin.serializers.spus import SPUSerializers, BrandSerializers, GoodsCategorySerializers
from meiduo_admin.utils import PageNum, SpuPermission


class SPUView(ModelViewSet):
    serializer_class =SPUSerializers
    queryset = SPU.objects.all()
    pagination_class = PageNum
    permission_classes = [IsAdminUser]
    permission_classes_by_action = {'create': [SpuPermission],
                                    'update': [SpuPermission],
                                    'destroy': [SpuPermission]
                                    }

    def get_permissions(self):
        try:
            # return permission_classes depending on `action`
            return [permission() for permission in self.permission_classes_by_action[self.action]]
        except KeyError:
            # action is not set return default permission_classes
            return [permission() for permission in self.permission_classes]

    def simple(self,request):
        brands = Brand.objects.all()
        ser = BrandSerializers(brands,many=True)
        return Response(ser.data)

    def categories(self,request):
        categories = GoodsCategory.objects.filter(parent=None)
        ser = GoodsCategorySerializers(categories,many=True)
        return Response(ser.data)

    def category_subs(self,request,pk):
        category = GoodsCategory.objects.get(id=pk)
        ser = GoodsCategorySerializers(category)
        return Response(ser.data)

    def images(self,request):
        file = request.FILES.get('image')
        file_bin = file.read()
        # 创建FastDFS客户端实例
        client = Fdfs_client(settings.FDFS_CONFIG_DIRS)
        # 调用FastDFS客户端上传文件方法
        ret = client.upload_by_buffer(file_bin)
        if ret['Status'] != 'Upload successed.':
            raise serializers.ValidationError('上传图片失败')
        return Response({
            'img_url':settings.FDFS_BASE_URL +ret['Remote file_id']
        })




